#include "client.h"
#include <boost/bind.hpp>
#include "connection.h"
#include "log.h"

namespace jump{

	namespace client{

		Client::Client(const std::string& arg_server,const std::string& arg_port,int arg_connectLimit)
			:ioService_(),
			resolver_(ioService_),
			connectLimit(arg_connectLimit)
		{
			tcp::resolver::query query(arg_server, arg_port);
			resolver_.async_resolve(query,
				boost::bind(&Client::handle_resolve, this,
				boost::asio::placeholders::error,
				boost::asio::placeholders::iterator));
		}

		void Client::run()
		{
			ioService_.run();
		}

		void Client::toConnect()
		{
			if(connectLimit<=0)
				return;
			newConnection_.reset(new Connection(ioService_,connectionMgr_));

			boost::asio::async_connect(newConnection_->socket(),iterators_,
				boost::bind(&Client::handle_connect,this,
				boost::asio::placeholders::error));
		}

		void Client::handle_resolve(const boost::system::error_code& arg_err,tcp::resolver::iterator arg_endpoint_iterator)
		{

			if(!arg_err)
			{
				iterators_=arg_endpoint_iterator;

				toConnect();
			}
			else 
			{
				LOG_ERR("Error in handle_resolve",arg_err.message());
				return;
			}

		}


		void Client::handle_connect(const boost::system::error_code& arg_err)
		{
			if(!arg_err)
			{
				//LOG_INFO("New Connection set");
				
				connectionMgr_.start(newConnection_);

				connectLimit--;

				toConnect();
				
			}else
			{
				LOG_ERR("Error in handle connect:",arg_err.message());
				return;
			}

		}

	}//namespace client
}//namespace jump
